package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.changdao.common.data.RespCodeEnum;
import com.yx.changdao.common.data.ResultCodeEnum;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.utils.DesensitizationUtils;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.IDCheck;
import com.yx.changdao.common.vo.BuildBuildVo;
import com.yx.changdao.service.*;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.SysUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: <br/>
 * 户信息表
 * <p>
 * <br/>
 * @Auther: walter
 * @create 2020/04/02 14:20
 */
@Validated
@RestController
@RequestMapping("community/build/detail")
public class CommunityBuildDetailController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CommunityBuildService communityBuildService;

    /**
     * 户的服务
     */
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;
    @Autowired
    private CommunityResidentService communityResidentService;
    /**
     * 部门联户人小组服务
     */
    @Autowired
    private DepContactGroupService depContactGroupService;

    /**
     * 列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
    public Result list() throws AlertException {
        return Result.ok().data(communityBuildDetailService.list(SysUtils.autoCnd(CommunityBuildDetail.class)
        .orderByDesc(CommunityBuildDetail.CREATE_TIME)));
    }


    /**
     * 添加户信息表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
    public Result add(@RequestBody @Valid CommunityBuildDetail communityBuildDetail) throws AlertException {
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, communityBuildDetail.getBuildId())
                .eq(CommunityBuildDetail.UNIT, communityBuildDetail.getUnit())
                .eq(CommunityBuildDetail.DOOR_PLATE, communityBuildDetail.getDoorPlate()));
        if(list.size()!=0){
            return Result.error("该户已存在");
        }

        //验证户信息
        verification(communityBuildDetail);
        boolean b = communityBuildDetailService.save(communityBuildDetail);

        if (!b) {
            throw new AlertException("添加失败");
        }
        CommunityBuildDetail one = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, communityBuildDetail.getBuildId())
                .eq(CommunityBuildDetail.UNIT, communityBuildDetail.getUnit())
                .eq(CommunityBuildDetail.DOOR_PLATE, communityBuildDetail.getDoorPlate()));
        BuildBuildVo buildBuildVo = new BuildBuildVo();
        buildBuildVo.setId(one.getId());
        buildBuildVo.setName(one.getDoorPlate());
        buildBuildVo.setUnit(one.getUnit());
        return Result.ok("添加成功").data(buildBuildVo);
    }


    /**
     * 获得指定id 户信息表。
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id) throws AlertException {
        CommunityBuildDetail communityBuildDetail = communityBuildDetailService.getById(id);
        communityBuildDetail.setIdCard(DesensitizationUtils.idEncrypt(communityBuildDetail.getIdCard()));
        communityBuildDetail.setLinkIdCard(DesensitizationUtils.idEncrypt(communityBuildDetail.getLinkIdCard()));
        communityBuildDetail.setLinkIdCard2(DesensitizationUtils.idEncrypt(communityBuildDetail.getLinkIdCard2()));
        CommunityBuild communityBuild = communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.ID, communityBuildDetail.getBuildId()));
        communityBuildDetail.setBuildType(communityBuild.getBuildType());
        if (communityBuildDetail == null) {
            throw new AlertException("未找到相关户信息信息");
        }

        return Result.ok().data(communityBuildDetail);
    }


    /**
     * 更新户信息表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
    public Result update(@RequestBody @Valid CommunityBuildDetail communityBuildDetail) throws AlertException {
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, communityBuildDetail.getBuildId())
                .eq(CommunityBuildDetail.UNIT, communityBuildDetail.getUnit())
                .eq(CommunityBuildDetail.DOOR_PLATE, communityBuildDetail.getDoorPlate()));
        if(list.size()!=0&&!list.get(0).getId().equals(communityBuildDetail.getId())){
            return Result.error("该户已存在");
        }
        //验证
        verification(communityBuildDetail);

        boolean b = communityBuildDetailService.updateById(communityBuildDetail);
        if (!b) {
            throw new AlertException("户信息更新失败");
        }

        return Result.ok("户信息更新成功");
    }


    /**
     * 删除户信息表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = {Exception.class})
    public Result delete(@PathVariable("id") String id) throws AlertException {
        CommunityBuildDetail one = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>().eq(CommunityBuildDetail.ID, id));
        BuildBuildVo buildBuildVo =new BuildBuildVo();
        buildBuildVo.setName(one.getDoorPlate());
        buildBuildVo.setId(one.getId());
        buildBuildVo.setUnit(one.getUnit());

        //删除户下面的居民
//        boolean b1 = communityBuildDetailService.removeResident(Integer.parseInt(id));
//        if (!b1) {
//            throw new AlertException("户信息删除失败");
//        }
        //查看户里面是否有居民
        List<CommunityResident> list =
                communityResidentService.list(new QueryWrapper<CommunityResident>().eq(CommunityResident.BUILD_DETAIL_ID, id));
        if(list.size()!=0){
            return new Result(RespCodeEnum.OK, null, ResultCodeEnum.DELETE, "您删除的层级内包含其他数据信息!", buildBuildVo);
        }


        //删除户
        boolean b = communityBuildDetailService.removeById(id);
        if (!b) {
            throw new AlertException("户信息删除失败");
        }

        return Result.ok("删除户信息成功").data(buildBuildVo);
    }


    /**
     * 根据建筑id查户
     * @return
     */
    @AutoLog
    @GetMapping("/getBuildByRegionId")
    public Result  getBuidDetailByBuildId(@RequestParam("buildId") Integer buildId){
        List<CommunityBuildDetail> buidDetailByBuildId = communityBuildDetailService.getBuidDetailByBuildId(buildId);
        List<BuildBuildVo> buildBuildVoList=new ArrayList<>();
        for (CommunityBuildDetail communityBuildDetail : buidDetailByBuildId) {
            BuildBuildVo buildBuildVo=new BuildBuildVo();

            buildBuildVo.setId(communityBuildDetail.getId());
            buildBuildVo.setName(communityBuildDetail.getDoorPlate());
            buildBuildVo.setParent_id(buildId);
            buildBuildVo.setUnit(communityBuildDetail.getUnit());

            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok("查询成功").data(buildBuildVoList);
    }
    /**
     * 根据建筑id查单元
     * @return
     */
    @AutoLog
    @GetMapping("/getUnitByBuildId")
    @RequiresPermissions("community:build:list")
    @ShiroDesc("社区建筑物表:列表")
    public Result  getUnitByBuildId(@RequestParam("buildId") Integer buildId){
        List<CommunityBuildDetail> buidDetailByBuildId = communityBuildDetailService.getBuidDetailByBuildId(buildId);
        List<BuildBuildVo> buildBuildVoList=new ArrayList<>();
        for (CommunityBuildDetail communityBuildDetail : buidDetailByBuildId) {
            BuildBuildVo buildBuildVo=new BuildBuildVo();
            buildBuildVo.setId(communityBuildDetail.getId());
            buildBuildVo.setName(communityBuildDetail.getDoorPlate());
            buildBuildVo.setParent_id(buildId);
            buildBuildVo.setUnit(communityBuildDetail.getUnit());
            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok("查询成功").data(buildBuildVoList);
    }

    /**
     * 根据建筑id和单元查户
     * @param buildId
     * @param unit
     * @return
     */
    @AutoLog
    @GetMapping("/gethouseNumberByBuildId")
    public Result  gethouseNumberByBuildId(@RequestParam("buildId") Integer buildId,
                                           @RequestParam("Unit")Integer unit){
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, buildId)
                .eq(CommunityBuildDetail.UNIT, unit)
        .orderByDesc(CommunityBuildDetail.CREATE_TIME));

        return Result.ok("查询成功").data(list);
    }
    /**
     * 根据身份证查id
     * @param
     * @param
     * @return
     */
    @AutoLog
    @GetMapping("/gethouseNumberByIdCard")
    @RequiresPermissions("community:build:list")
    @ShiroDesc("社区建筑物表:列表")
    public Result  gethouseNumberByIdCard(@RequestParam("idCard") String idCard){
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.ID_CARD, idCard)
        .orderByDesc(CommunityBuildDetail.CREATE_TIME));

        return Result.ok("查询成功").data(list);
    }

    /**
     * 导入  按照楼导入户
     */
    @AutoLog
    @PostMapping("/checkAndSave")
    public Result checkAndSave(@RequestParam("communityBuildDent") MultipartFile communityBuildDent) throws AlertException {
        /**
         * 保存正常的，返回异常的
         */
        Map<String, Object> map = communityBuildDetailService.checkAndSave(communityBuildDent);
        return Result.ok().data(map);
    }
    @AutoLog
    @GetMapping("/template")
    public void template(HttpServletResponse response) throws AlertException, IOException {
        File cfgFile = ResourceUtils.getFile("classpath:public/户统一表头 .xlsx");

        Faster.download(response,cfgFile);
    }
    /**
     * 对应联户组下的户
     * @param buildId
     * @return
     * @throws AlertException
     */
    @AutoLog
    @GetMapping("/getListByContactGroup")
    public Result getListByContactGroup(@RequestParam("buildId")Integer buildId) throws AlertException {
        String userId = SysUtils.currentUserId();
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
        if (sysUser == null) {
            return Result.error("该帐号不存在");
        }
        List<BuildBuildVo> buildBuildVoList = new ArrayList<>();
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, buildId)
                .eq(CommunityBuildDetail.CONTACT_GROUP_ID, sysUser.getContactGroupId()));
        for (CommunityBuildDetail communityBuildDetail : list) {
            BuildBuildVo buildBuildVo=new BuildBuildVo();
            buildBuildVo.setId(communityBuildDetail.getId());
            buildBuildVo.setName(communityBuildDetail.getDoorPlate());
            buildBuildVo.setParent_id(buildId);
            buildBuildVo.setUnit(communityBuildDetail.getUnit());
            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok("成功").data(buildBuildVoList);
    }

    /**
     * 户的验证信息
     * @param communityBuildDetail
     * @throws AlertException
     */
    public void verification(CommunityBuildDetail communityBuildDetail) throws AlertException {
        if(communityBuildDetail.getUnit()==null){
            throw new AlertException("单元/排号不能为空");
        }
        //0:是空户 1:非空户
        if(communityBuildDetail.getHouseEmpty()==1){
            if(Strings.isBlank(communityBuildDetail.getUserName())){
                throw new AlertException("户主名称不允许为空");
            }
            if(Strings.isBlank(communityBuildDetail.getPhone())){
                throw new AlertException("户主手机号不允许为空");
            }
            if(communityBuildDetail.getRent()==null){
                throw new AlertException("是否租住户不能为空");
            }
            if(communityBuildDetail.getFamilyPopulationNum()==null){
                throw new AlertException("家庭人口数不能为空");
            }
        }
        /*if(Strings.isNotBlank(communityBuildDetail.getPhone())){
            boolean matches = communityBuildDetail.getPhone().matches("^1[0-9]{10}$");
            if(matches==false){
                throw new AlertException("请输入正确的户主电话");
            }
        }*/
        if(Strings.isNotBlank(communityBuildDetail.getLinkPhone())){
            boolean matches = communityBuildDetail.getLinkPhone().matches("^1[0-9]{10}$");
            if(matches==false){
                throw new AlertException("请输入正确的联络人电话");
            }
        }
        if(Strings.isNotBlank(communityBuildDetail.getLinkPhone2())){
            boolean matches = communityBuildDetail.getLinkPhone2().matches("^1[0-9]{10}$");
            if(matches==false){
                throw new AlertException("请输入正确的联络人电话");
            }
        }
        if(Strings.isNotBlank(communityBuildDetail.getIdCard())){
            if (communityBuildDetail.getIdCard().length() != 15 && communityBuildDetail.getIdCard().length() != 18) {
                throw new AlertException("身份证不合法");
            }
        }
        DepContactGroup depContactGroup = depContactGroupService.
                getOne(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID, communityBuildDetail.getContactGroupId()));
        if(depContactGroup==null){
            throw new AlertException("该小组不存在");
        }
        communityBuildDetail.setGroupName(depContactGroup.getGroupName());
    }
}
